package com.example.myvertx;

import com.example.myvertx.handler.GetPetHandler;
import com.example.myvertx.handler.HelloHandler;
import com.example.myvertx.handler.PostPetHandler;
import io.vertx.config.ConfigRetriever;
import io.vertx.config.ConfigRetrieverOptions;
import io.vertx.config.ConfigStoreOptions;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.LoggerFormat;
import io.vertx.ext.web.handler.impl.LoggerHandlerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MainVerticle extends AbstractVerticle {

  private final Logger log = LoggerFactory.getLogger(MainVerticle.class);

  @Override
  public void start(Promise<Void> startPromise) {
    ConfigStoreOptions store = new ConfigStoreOptions()
      .setType("file")
      .setFormat("yaml")
      .setConfig(new JsonObject().put("path", "my-config.yaml"));

    ConfigRetriever retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(store));

    Router router = Router.router(vertx);
    router.route().handler(new LoggerHandlerImpl(LoggerFormat.DEFAULT));
    router.route("/hello").handler(new HelloHandler());
    router.get("/pet").respond(new GetPetHandler());
    router.post("/pet").handler(BodyHandler.create()).respond(new PostPetHandler());


    HttpServer server = vertx.createHttpServer();

    retriever.getConfig().onComplete(json -> {
      JsonObject result = json.result();

      Integer port = result.getInteger("port");

      server.requestHandler(router)
        .listen(port)
        .onComplete(ar -> {
          if (ar.succeeded()) {
            startPromise.complete();
            log.info("HTTP server started on port {}(http://localhost:{})", port, port);
          } else {
            startPromise.fail(ar.cause());
          }
        });
    });
  }
}
